<?php

use app\admin\constants\CacheConstants;
use app\exception\ParamException;
use app\model\AdminModel;
use app\model\AdminRolesModel;
use Shopwwi\LaravelCache\Cache;

/**
 * Here is your custom functions.
 */


 
 //返回请求类型 http:// or https://
 function get_http_type(){
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

    return $http_type;
}

//获取当前管理员id
function get_admin_id(){
    $request = request();

    return $request->admin_id ?? 0;
}

//获取管理员角色权限
function get_admin_rules_ids($admin_id = null, $is_update = false){

    $admin_id = $admin_id ?? get_admin_id();

    if(!$admin_id){
        return [];
    }

    $rules = Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->get('admin_rules_2_'.$admin_id);

    if(!$rules || $is_update){
        $adminModel = new AdminModel();
        $admin = $adminModel->find($admin_id);
        $rolesModel = new AdminRolesModel();
        $roles = $rolesModel->where("id",'in',$admin['roles'])->select();

        if(!$roles) return [];

        $rules = [];
        foreach($roles as $k=>$v){
            $rules = array_merge($rules,explode(",",$v['rules']));
        }

        //清除数组空内容，清除数组重复内容
        $rules = array_filter(array_unique($rules));

        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->set('admin_rules_2_'.$admin_id,$rules,CacheConstants::CACHE_TTL);
    }

    return $rules;
}



//获取当前管理员信息
function get_admin_info($id = null,$is_update = false){

    $request = request();

    $admin_id = $id ?? $request->admin_id;

    if(!$admin_id) throw new ParamException();

    $admin = Cache::get('admin_info_'.$admin_id);
    if(!$admin || $is_update){
        $admin = AdminModel::where("id",$admin_id)->hidden(['password'])->find();
        if($admin){
            $admin = $admin->toArray();
            Cache::set('admin_info_'.$admin_id,$admin,CacheConstants::CACHE_TTL);
        }else{
            $admin = [];
        }
    }

    return $admin;
}

//判断是否是post请求
function is_post(){
    $request = request();
   
    return $request->method() == 'POST' ? true:false;
}


//判断是否是get请求
function is_get(){
    $request = request();
   

    return $request->method() == 'GET' ? true:false;
}

/**
 * 登录密码加密
 * $password 密码
 * $salt 加密盐
 */
function get_password($password,$salt=''){

    return '###'.md5(md5($password.$salt));
}

/**
 * 检查手机格式，中国手机不带国家代码，国际手机号格式为：国家代码-手机号
 * @param $mobile
 * @return bool
 */
function check_mobile($mobile)
{
    if (preg_match('/(^(13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{8})$/', $mobile)) {
        return true;
    } else {
        if (preg_match('/^\d{1,4}-\d{5,11}$/', $mobile)) {
            if (preg_match('/^\d{1,4}-0+/', $mobile)) {
                //不能以0开头
                return false;
            }

            return true;
        }

        return false;
    }
}